//
//  UIViewController+Category.m
//  Paoword
//
//  Created by 欧杜书 on 16/5/25.
//  Copyright © 2016年 New. All rights reserved.
//

#import "UIViewController+Category.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "UIImage+Color2Image.h"
#import "UIBarButtonItem+BlocksKit.h"
#import <objc/runtime.h>

@implementation UIViewController (Category)


static char callbackAddrKey = 'l';
- (navigationLeftItemCallback)leftItemCallback
{
    return objc_getAssociatedObject(self, &callbackAddrKey);
}

- (void)setLeftItemCallback:(navigationLeftItemCallback)leftItemCallback
{
    objc_setAssociatedObject(self, &callbackAddrKey, leftItemCallback, OBJC_ASSOCIATION_COPY_NONATOMIC);
}


+ (UIViewController *)pw_currentViewController {
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    result = window.rootViewController;
    if (window.subviews.count > 0) {
        UIView *frontView = window.subviews.firstObject;
        id nextResponder = [frontView nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            result = nextResponder;
        }
    }
    return [self findFrontController:result];
}

+ (UIViewController *)findFrontController:(UIViewController *)vc {
    if (vc.presentedViewController) {
        vc = vc.presentedViewController;
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        vc = ((UITabBarController *)vc).selectedViewController;
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        vc = ((UINavigationController *)vc).childViewControllers.lastObject;
    } else {
        return vc;
    }
    return [self findFrontController:vc];
}

+ (UIView *)pw_currentViewControllerView {
    UIViewController *vc = [UIViewController pw_currentViewController];
    return vc.view;
}

/**
 *  隐藏导航栏
 */
- (void)pw_setNavigationBarHidden {
    self.fd_prefersNavigationBarHidden = YES;
}
/**
 *  设置导航栏颜色
 */
//- (void)pw_setNavigationBarColor:(UIColor *)color tintColor:(UIColor *)tintColor {
//    [self pw_setNavigationBarHidden];
//}
/**
 *  隐藏导航栏（只有title）
 */
- (void)pw_setNavigationBarTransparentOnlyWithTitle:(NSString *)title tintColor:(UIColor *)tintColor {
    [self pw_setNavigationBarHidden];
    UIBarButtonItem *spaceItem = [self spaceItem];
    UIBarButtonItem *titleItem = [self titleItemWithTitle:title];
    UIToolbar *toobar = [self toolBarWithTintColor:tintColor];
    [toobar setItems:@[spaceItem, titleItem, spaceItem] animated:YES];
}
/**
 *  隐藏导航栏（有返回按钮）
 */
- (void)pw_setNavigationBarTransparentWithTintColor:(UIColor *)tintColor {
    [self pw_setNavigationBarTransparentWithLeftItemImage:nil title:nil rightBarButtonItems:nil tintColor:tintColor];
}
/**
 *  隐藏导航栏（有返回按钮及title）
 */
- (void)pw_setNavigationBarTransparentWithTitle:(NSString *)title tintColor:(UIColor *)tintColor {
    [self pw_setNavigationBarTransparentWithLeftItemImage:nil title:title rightBarButtonItems:nil tintColor:tintColor];
}
/**
 *  隐藏导航栏（有返回按钮及右边的items）
 */
- (void)pw_setNavigationBarTransparentWithRightBarButtonItems:(NSArray<UIBarButtonItem *> *)items tintColor:(UIColor *)tintColor {
    [self pw_setNavigationBarTransparentWithLeftItemImage:nil title:nil rightBarButtonItems:items tintColor:tintColor];
}
/**
 *  隐藏导航栏（有返回按钮和title及右边的items）
 */
- (void)pw_setNavigationBarTransparentWithLeftItemImage:(NSString *)leftItemImage
                                                  title:(NSString *)title
                                    rightBarButtonItems:(NSArray<UIBarButtonItem *> *)items
                                              tintColor:(UIColor *)tintColor {
    [self pw_setNavigationBarHidden];
    UIToolbar *toolBar = [self toolBarWithTintColor:tintColor];
    [self.view addSubview:toolBar];
    UIBarButtonItem *backItem = [self backBarButtonItemWithImage:leftItemImage];
    UIBarButtonItem *spaceItem = [self spaceItem];
    UIBarButtonItem *titleItem = [self titleItemWithTitle:title];
    NSMutableArray *itemArray = nil;
    if (items.count > 0 && title.length > 0) {
        itemArray = [NSMutableArray arrayWithArray:@[backItem, spaceItem, titleItem, spaceItem]];
        [itemArray addObjectsFromArray:items];
    } else if (title.length > 0) {
        itemArray = [NSMutableArray arrayWithArray:@[backItem, spaceItem, titleItem, spaceItem]];
    } else if (items.count > 0) {
        itemArray = [NSMutableArray arrayWithArray:@[backItem, spaceItem]];
        [itemArray addObjectsFromArray:items];
    } else {
        itemArray = [NSMutableArray arrayWithObject:backItem];
    }
    [toolBar setItems:itemArray animated:YES];
}

/**
 *  隐藏导航栏（无返回按钮 及 有右边的items）
 */
- (void)pw_setNavigationBarTransparentWithoutLeftBarWithRightBarButtonItems:(NSArray<UIBarButtonItem *> *)items tintColor:(UIColor *)tintColor {
    [self pw_setNavigationBarTransparentWithoutLeftBarWithTitle:nil rightBarButtonItems:items tintColor:tintColor];
}
/**
 *  隐藏导航栏（无返回按钮 和 有title及右边的items）
 */
- (void)pw_setNavigationBarTransparentWithoutLeftBarWithTitle:(NSString *)title rightBarButtonItems:(NSArray<UIBarButtonItem *> *)items tintColor:(UIColor *)tintColor {
    [self pw_setNavigationBarHidden];
    UIToolbar *toolBar = [self toolBarWithTintColor:tintColor];
    //wangyufei toolBarWithTintColor 函数中已经add过了 不需要再次add
//    [self.view addSubview:toolBar];
    UIBarButtonItem *spaceItem = [self spaceItem];
    UIBarButtonItem *titleItem = [self titleItemWithTitle:title];
    NSMutableArray *itemArray = nil;
    if (items.count > 0 && title.length > 0) {
        itemArray = [NSMutableArray arrayWithArray:@[ spaceItem, titleItem, spaceItem]];
        [itemArray addObjectsFromArray:items];
    } else if (title.length > 0) {
        itemArray = [NSMutableArray arrayWithArray:@[ spaceItem, titleItem, spaceItem]];
    } else if (items.count > 0) {
        itemArray = [NSMutableArray arrayWithArray:@[ spaceItem]];
        [itemArray addObjectsFromArray:items];
    }
    [toolBar setItems:itemArray animated:YES];
}

- (BOOL)pw_presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {
    if (!self.presentedViewController && viewControllerToPresent) {
        [self presentViewController:viewControllerToPresent animated:flag completion:completion];
        return YES;
    }else if(![self.presentingViewController isKindOfClass:[viewControllerToPresent class]] && viewControllerToPresent){
        [self.presentingViewController presentViewController:viewControllerToPresent animated:flag completion:completion];
        return YES;
    }else{
        return NO;
    }
}

- (UIToolbar *)toolBarWithTintColor:(UIColor *)tintColor {
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 44)];
    [self.view addSubview:toolBar];
    toolBar.translucent = YES;
    toolBar.tintColor = tintColor;
    [toolBar setBackgroundImage:[UIImage mmg_imageWithColor:[UIColor clearColor]] forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [toolBar setShadowImage:[UIImage mmg_imageWithColor:[UIColor clearColor]] forToolbarPosition:UIBarPositionAny];
    return toolBar;
}

- (UIBarButtonItem *)backBarButtonItemWithImage:(NSString *)imageName {
    UIImage *image = nil;
    if (imageName) {
        image = [UIImage imageNamed:imageName];
    } else {
        image = [UIImage imageNamed:@"backButtonImage"];
    }
    //wangyufei weakself防止循环引用
    MMGWeakSelf(weakSelf);
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] bk_initWithImage:image style:UIBarButtonItemStylePlain handler:^(id sender) {
        if (weakSelf.leftItemCallback) {
            weakSelf.leftItemCallback();
        }else
            [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    if (!imageName) {
        backItem.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return backItem;
}

- (UIBarButtonItem *)spaceItem {
    return [[UIBarButtonItem alloc] bk_initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace handler:nil];
}

- (UIBarButtonItem *)titleItemWithTitle:(NSString *)title {
    return [[UIBarButtonItem alloc] bk_initWithTitle:title style:UIBarButtonItemStylePlain handler:nil];
}

@end

@implementation UINavigationController (ShouldPopOnBackButton)

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
    if(self.viewControllers.count < navigationBar.items.count) return YES;
    
    BOOL shouldPop = YES;
    UIViewController *vc = [self topViewController];
    if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
        shouldPop = [vc navigationShouldPopOnBackButton];
    }
    
    if(shouldPop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self popViewControllerAnimated:YES];
        });
    } else {
        // Workaround for iOS7.1. Thanks to @boliva - http://stackoverflow.com/posts/comments/34452906
        for(UIView *subview in navigationBar.subviews) {
            if(subview.alpha < 1.0) {
                [UIView animateWithDuration:0.25 animations:^{
                    subview.alpha = 1.0;
                }];
            }
        }
    }
    
    return NO;
}




@end
